package com.liuxingzhiwu.ruijishangcheng.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuxingzhiwu.ruijishangcheng.common.R;
import com.liuxingzhiwu.ruijishangcheng.dto.DishDto;
import com.liuxingzhiwu.ruijishangcheng.entity.Dish;
import com.liuxingzhiwu.ruijishangcheng.entity.DishFlavor;
import com.liuxingzhiwu.ruijishangcheng.service.DishFlavorService;
import com.liuxingzhiwu.ruijishangcheng.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;  //菜品

    @Autowired
    private DishFlavorService dishFlavorService;  //口味


    /**
     * 菜品分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        //分类条件
        Page pageInfo = new Page<>(page,pageSize);

        //菜品筛选条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        if(name!=null) {
            queryWrapper.like(Dish::getName, name);
        }

        //分类查询
        Page<Dish> pageDish = dishService.page(pageInfo,queryWrapper);

        return R.success(pageDish);
    }

    /**
     * 添加菜品
     * @param request
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody DishDto dishDto){

        dishService.saveWithFlavor(request,dishDto);

        return R.success("添加成功");
    }

    /**
     *回显菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getEditDish(@PathVariable("id") Long id){

        //按主键id查找菜品信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,id);
        //查询菜品口味
        List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
        //查询菜品
        Dish dish = dishService.getById(id);
        DishDto dishDto = new DishDto();
        //这里要记住，将dish的值赋值给dishDto,,,,dish是dishDto的父类
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(dishFlavorList);
        return R.success(dishDto);
    }


    /**
     * 修改菜品信息（包括口味）
     * @param request
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateDish(HttpServletRequest request,@RequestBody DishDto dishDto){

        dishService.updateWithFlavor(request,dishDto);

        return R.success("修改成功");
    }


    /**
     * 修改菜品状态，起售和停售
     * @param request
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(HttpServletRequest request,@PathVariable("status") Integer status,Long[] ids){

        Dish dish = new Dish();
        Long empId = (Long) request.getSession().getAttribute("employee");
        for (Long id:ids) {
            dish.setId(id);

            dish.setStatus(status);

            dish.setUpdateTime(LocalDateTime.now());


            dish.setUpdateUser(empId);

            dishService.updateById(dish);
        }

        return R.success("操作成功");
    }

    /**
     * 删除菜品和口味
     * @param request
     * @param ids
     * @return
     */
    //DELETE http://localhost:8080/dish?ids=1397849739276890114
    @DeleteMapping
    @Transactional
    public R<String> deleteDish(HttpServletRequest request,Long[] ids){

        for (Long id:ids) {
            //删除菜品，连菜品口味一起删除
            QueryWrapper<Dish> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("id",id);
            dishService.remove(queryWrapper1);

            //删除菜品口味
            QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dish_id",id);
            dishFlavorService.remove(queryWrapper);
        }
        return R.success("删除成功");
    }

    /**
     * 包含口味展示
     * @param categoryId
     * @param name
     * @return
     */
    @GetMapping("/list")
    public R<List> getDish(Long categoryId,String name){

        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtils.isNotEmpty(categoryId),"category_id",categoryId);
        queryWrapper.like(StringUtils.isNotEmpty(name),"name",name);

        //查询菜品
        List<Dish> dishes = dishService.list(queryWrapper);

        List<DishDto> dishDtos = dishes.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            return dishDto;
        }).collect(Collectors.toList());


        //2、添加菜品口味（口味有多中是一个List数组）
        dishDtos = dishDtos.stream().map((item)->{
            QueryWrapper<DishFlavor> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("dish_id",item.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper1);
            item.setFlavors(dishFlavors);
            return item;
        }).collect(Collectors.toList());
        return R.success(dishDtos);
    }

}
